<template>
  <div class="banners-page">
    <!-- 页面标题 -->
    <t-card class="header-card">
      <div class="card-header">
        <h2 class="page-title">轮播图管理</h2>
        <t-button theme="primary" @click="handleAddBanner">
          <template #icon><t-icon name="add" /></template>
          新增轮播图
        </t-button>
      </div>
    </t-card>

    <!-- 轮播图列表 -->
    <t-card class="banner-list-card">
      <t-tabs v-model="activeTab" class="filter-tabs">
        <t-tab-panel value="all" label="全部" />
        <t-tab-panel value="active" label="已启用" />
        <t-tab-panel value="inactive" label="已禁用" />
      </t-tabs>

      <t-loading :loading="loading">
        <div class="banner-grid">
          <t-row :gutter="[16, 16]">
            <t-col v-for="(banner, index) in displayBanners" :key="banner.id" :xs="24" :sm="12" :md="8" :lg="6">
              <t-card class="banner-card" :class="{ inactive: !banner.isActive }" :bordered="true" :hover="true">
                <!-- 轮播图预览 -->
                <div class="banner-image-wrapper">
                  <img class="banner-image" :src="banner.imageUrl" :alt="banner.title" />
                  <div v-if="!banner.isActive" class="banner-status inactive">已禁用</div>
                  <div v-else class="banner-status active">已启用</div>
                  <div class="banner-order">{{ index + 1 }}</div>
                </div>

                <!-- 轮播图信息 -->
                <div class="banner-info">
                  <div class="banner-title">{{ banner.title }}</div>
                  <div class="banner-link">链接: {{ banner.link || '无' }}</div>
                  <div class="banner-position">位置: {{ getPositionName(banner.position) }}</div>
                </div>

                <!-- 操作按钮 -->
                <t-space class="banner-operations">
                  <t-button theme="primary" variant="text" @click="handleEditBanner(banner)">
                    <template #icon><t-icon name="edit" /></template>
                    编辑
                  </t-button>
                  <t-button v-if="banner.isActive" variant="text" theme="warning" @click="handleToggleStatus(banner)">
                    <template #icon><t-icon name="close-circle" /></template>
                    禁用
                  </t-button>
                  <t-button v-else variant="text" theme="success" @click="handleToggleStatus(banner)">
                    <template #icon><t-icon name="check-circle" /></template>
                    启用
                  </t-button>
                  <t-popconfirm content="确认删除该轮播图吗？" @confirm="handleDeleteBanner(banner)">
                    <t-button variant="text" theme="danger">
                      <template #icon><t-icon name="delete" /></template>
                      删除
                    </t-button>
                  </t-popconfirm>
                </t-space>
              </t-card>
            </t-col>
          </t-row>
        </div>
      </t-loading>

      <!-- 空状态 -->
      <t-empty v-if="displayBanners.length === 0" description="暂无数据">
        <template #image>
          <t-icon name="image" style="font-size: 64px; color: #ddd;" />
        </template>
        <t-button @click="handleAddBanner">新增轮播图</t-button>
      </t-empty>
    </t-card>

    <!-- 轮播图表单对话框 -->
    <t-dialog
      v-model:visible="dialogVisible"
      :header="isEdit ? '编辑轮播图' : '新增轮播图'"
      width="600px"
      :footer="false"
      @close="resetForm"
    >
      <t-form
        ref="form"
        :data="formData"
        :rules="rules"
        :label-width="80"
        @submit="handleSubmit"
      >
        <t-form-item label="标题" name="title">
          <t-input v-model="formData.title" placeholder="请输入轮播图标题" />
        </t-form-item>
        
        <t-form-item label="图片" name="imageUrl">
          <t-upload
            v-model="formData.imageFile"
            theme="image"
            :before-upload="handleBeforeUpload"
            accept="image/*"
          >
            <template #tip>
              <p class="tip-text">支持jpg/png格式，建议尺寸1920*500px，大小不超过2M</p>
            </template>
          </t-upload>
        </t-form-item>
        
        <t-form-item label="链接" name="link">
          <t-input v-model="formData.link" placeholder="请输入轮播图链接，可选" />
        </t-form-item>
        
        <t-form-item label="展示位置" name="position">
          <t-select v-model="formData.position" placeholder="请选择展示位置">
            <t-option v-for="item in positionOptions" :key="item.value" :value="item.value" :label="item.label" />
          </t-select>
        </t-form-item>
        
        <t-form-item label="状态" name="isActive">
          <t-radio-group v-model="formData.isActive">
            <t-radio :value="true">启用</t-radio>
            <t-radio :value="false">禁用</t-radio>
          </t-radio-group>
        </t-form-item>
        
        <t-form-item label="排序" name="order">
          <t-input-number v-model="formData.order" :min="1" />
        </t-form-item>
        
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="dialogVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitting">确定</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 排序对话框 -->
    <t-dialog
      v-model:visible="sortDialogVisible"
      header="调整轮播图顺序"
      width="600px"
    >
      <t-list class="sort-list">
        <t-list-item
          v-for="(item, index) in sortableBanners"
          :key="item.id"
          class="sort-item"
        >
          <template #avatar>
            <div class="sort-handle">
              <t-icon name="move" />
            </div>
            <div class="sort-index">{{ index + 1 }}</div>
          </template>
          <t-list-item-meta
            :title="item.title"
          >
            <template #image>
              <img class="sort-image" :src="item.imageUrl" :alt="item.title" />
            </template>
          </t-list-item-meta>
        </t-list-item>
      </t-list>
      <template #footer>
        <t-space>
          <t-button theme="default" @click="sortDialogVisible = false">取消</t-button>
          <t-button theme="primary" @click="saveSortOrder" :loading="sortSubmitting">保存</t-button>
        </t-space>
      </template>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

// 定义类型接口
interface Banner {
  id: string;
  title: string;
  imageUrl: string;
  link: string;
  position: string;
  isActive: boolean;
  order: number;
  createTime: string;
}

interface UploadFile {
  name: string;
  url: string;
}

interface PositionOption {
  label: string;
  value: string;
}

// 位置选项
const positionOptions: PositionOption[] = [
  { label: '首页头部', value: 'home_top' },
  { label: '首页中部', value: 'home_middle' },
  { label: '活动页面', value: 'activity' },
  { label: '景点页面', value: 'spot' },
]

// 状态管理
const loading = ref(false)
const submitting = ref(false)
const sortSubmitting = ref(false)
const activeTab = ref('all')
const dialogVisible = ref(false)
const sortDialogVisible = ref(false)
const isEdit = ref(false)

// 轮播图数据
const banners = ref<Banner[]>([
  {
    id: '1',
    title: '四季康养夏日特惠',
    imageUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    link: '/activities/summer',
    position: 'home_top',
    isActive: true,
    order: 1,
    createTime: '2024-05-01',
  },
  {
    id: '2',
    title: '山林徒步活动',
    imageUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    link: '/activities/hiking',
    position: 'activity',
    isActive: true,
    order: 2,
    createTime: '2024-05-15',
  },
  {
    id: '3',
    title: '温泉养生之旅',
    imageUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    link: '/spots/hotspring',
    position: 'spot',
    isActive: false,
    order: 3,
    createTime: '2024-04-20',
  },
  {
    id: '4',
    title: '端午康养套餐',
    imageUrl: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
    link: '',
    position: 'home_middle',
    isActive: true,
    order: 4,
    createTime: '2024-06-01',
  },
])

// 表单数据
interface FormData {
  id: string;
  title: string;
  imageFile: UploadFile[];
  imageUrl: string;
  link: string;
  position: string;
  isActive: boolean;
  order: number;
}

const formData = reactive<FormData>({
  id: '',
  title: '',
  imageFile: [],
  imageUrl: '',
  link: '',
  position: 'home_top',
  isActive: true,
  order: 1,
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入轮播图标题', type: 'error' },
    { max: 30, message: '标题不能超过30个字符', type: 'warning' }
  ],
  position: [
    { required: true, message: '请选择展示位置', type: 'error' }
  ]
}

// 编辑的轮播图索引
const editIndex = ref(-1)

// 根据标签筛选轮播图
const displayBanners = computed(() => {
  if (activeTab.value === 'all') {
    return banners.value
  }
  return banners.value.filter(item => 
    activeTab.value === 'active' ? item.isActive : !item.isActive
  )
})

// 用于排序的轮播图列表
const sortableBanners = ref<Banner[]>([])

// 根据位置获取名称
const getPositionName = (position: string) => {
  const found = positionOptions.find(item => item.value === position)
  return found ? found.label : position
}

// 添加轮播图
const handleAddBanner = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑轮播图
const handleEditBanner = (banner: Banner) => {
  isEdit.value = true
  dialogVisible.value = true
  
  // 查找索引
  const index = banners.value.findIndex(item => item.id === banner.id)
  if (index !== -1) {
    editIndex.value = index
    
    // 填充表单数据
    formData.id = banner.id
    formData.title = banner.title
    formData.imageUrl = banner.imageUrl
    formData.link = banner.link
    formData.position = banner.position
    formData.isActive = banner.isActive
    formData.order = banner.order
    
    // 如果有图片，添加到上传列表中
    if (banner.imageUrl) {
      formData.imageFile = [{
        name: banner.title,
        url: banner.imageUrl,
      }]
    }
  }
}

// 删除轮播图
const handleDeleteBanner = (banner: Banner) => {
  const index = banners.value.findIndex(item => item.id === banner.id)
  if (index !== -1) {
    banners.value.splice(index, 1)
    MessagePlugin.success('删除成功')
  }
}

// 切换状态
const handleToggleStatus = (banner: Banner) => {
  const index = banners.value.findIndex(item => item.id === banner.id)
  if (index !== -1) {
    banners.value[index].isActive = !banners.value[index].isActive
    MessagePlugin.success(banners.value[index].isActive ? '已启用' : '已禁用')
  }
}

// 打开排序对话框
const handleSort = () => {
  sortableBanners.value = [...banners.value]
  sortDialogVisible.value = true
}

// 保存排序
const saveSortOrder = () => {
  sortSubmitting.value = true
  
  // 模拟保存操作
  setTimeout(() => {
    banners.value = [...sortableBanners.value]
    sortSubmitting.value = false
    sortDialogVisible.value = false
    MessagePlugin.success('排序已保存')
  }, 1000)
}

// 表单提交
const handleSubmit = async ({ validateResult }: { validateResult: boolean }) => {
  if (validateResult !== true) return
  
  submitting.value = true
  
  try {
    // 模拟异步操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟上传图片
    const imageUrl = formData.imageFile.length > 0
      ? formData.imageFile[0].url || 'https://tdesign.gtimg.com/site/source/figma-pc.png'
      : formData.imageUrl
    
    // 构造保存数据
    const saveData: Banner = {
      id: isEdit.value ? formData.id : `${Date.now()}`,
      title: formData.title,
      imageUrl,
      link: formData.link,
      position: formData.position,
      isActive: formData.isActive,
      order: formData.order,
      createTime: new Date().toISOString().split('T')[0]
    }
    
    // 保存操作
    if (isEdit.value) {
      // 编辑轮播图
      banners.value.splice(editIndex.value, 1, saveData)
      MessagePlugin.success('保存成功')
    } else {
      // 新增轮播图
      banners.value.push(saveData)
      MessagePlugin.success('添加成功')
    }
    
    dialogVisible.value = false
  } finally {
    submitting.value = false
  }
}

// 上传前校验
const handleBeforeUpload = (file: File) => {
  // 检查文件类型
  const isImage = /image\/(jpeg|png)/.test(file.type)
  if (!isImage) {
    MessagePlugin.warning('只能上传jpg/png格式图片')
    return false
  }
  
  // 检查文件大小，限制为2MB
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    MessagePlugin.warning('图片大小不能超过2MB')
    return false
  }
  
  return isImage && isLt2M
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.title = ''
  formData.imageFile = []
  formData.imageUrl = ''
  formData.link = ''
  formData.position = 'home_top'
  formData.isActive = true
  formData.order = banners.value.length + 1
  editIndex.value = -1
}
</script>

<style scoped>
.banners-page {
  padding: 16px;
}

.header-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.banner-list-card {
  margin-bottom: 16px;
}

.filter-tabs {
  margin-bottom: 16px;
}

.banner-grid {
  padding-bottom: 16px;
}

.banner-card {
  display: flex;
  flex-direction: column;
  height: 100%;
  transition: all 0.3s ease;
}

.banner-card.inactive {
  opacity: 0.6;
}

.banner-image-wrapper {
  position: relative;
  height: 120px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 12px;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-status {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.banner-status.active {
  background-color: rgba(0, 168, 112, 0.8);
  color: white;
}

.banner-status.inactive {
  background-color: rgba(227, 77, 89, 0.8);
  color: white;
}

.banner-order {
  position: absolute;
  top: 8px;
  left: 8px;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.banner-info {
  flex-grow: 1;
  margin-bottom: 12px;
}

.banner-title {
  font-weight: 600;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.banner-link,
.banner-position {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.banner-operations {
  border-top: 1px solid #eee;
  padding-top: 12px;
  display: flex;
  justify-content: space-between;
}

.tip-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 排序对话框相关样式 */
.sort-list {
  border: 1px solid #eee;
  border-radius: 4px;
}

.sort-item {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.sort-item:hover {
  background-color: #f5f5f5;
}

.sort-handle {
  cursor: move;
  color: #999;
  margin-right: 8px;
}

.sort-index {
  width: 24px;
  height: 24px;
  border-radius: 12px;
  background-color: #eee;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  margin-right: 12px;
}

.sort-image {
  width: 80px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}
</style> 